允许用户创建新条目
<template>
  <div class="c-select-create">
    <a-select
      v-model="selectVal"
      show-search
      @search="searchKey"
      :placeholder="placeholder"
      @change="change"
    >
      <a-select-option :key="item.title" v-for="item in options">{{
        item.title
      }}</a-select-option>
    </a-select>
  </div>
</template>

<script>
import { debounce } from "@/util/common";

export default {
  props: {
    value: {
      type: String
    },
    // 初始数据
    data: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 占位符
    placeholder: {
      type: String,
      default: "请输入"
    }
  },
  data() {
    return {
      defaultOptions: [], // 初始选项
      options: []
    };
  },
  computed: {
    selectVal: {
      get() {
        return this.value;
      },
      set(n) {
        this.$emit("input", n);
      }
    }
  },
  methods: {
    searchKey: debounce(function(value) {
      let res = [];
      this.options.forEach(item => {
        if (item.title.includes(value)) {
          res.push(item);
        }
      });
      if (res.length === 0) {
        this.options.unshift({
          title: value
        });
      } else {
        this.options = res;
      }
    }),
    change(val) {
      // 选中后可选选项恢复默认
      this.options = this.defaultOptions;
      this.$emit("change", val);
    }
  },
  created() {
    this.defaultOptions = this.data;
    this.options = this.data;
  }
};
</script>
